﻿
#region Usings
using System.Text;
#endregion

namespace LongNet.Security
{
    /// <summary>
    /// Encrypts a string using Caesar encryption
    /// </summary>
    public static class CaesarEncryption
    {
        #region Public Static Functions

        /// <summary>
        /// Encrypts a string using Caesar encryption
        /// </summary>
        /// <param name="Input">Input string</param>
        /// <param name="Key">Key to encrypt with (can be any length)</param>
        /// <returns>An encrypted string</returns>
        public static string Encrypt(string Input, string Key)
        {
            return Process(Input, Key);
        }

        /// <summary>
        /// Decrypts a string using Caesar encryption
        /// </summary>
        /// <param name="Input">Input string</param>
        /// <param name="Key">Key to decrypt with (can be any length)</param>
        /// <returns>A decrypted string</returns>
        public static string Decrypt(string Input, string Key)
        {
            return Process(Input, Key);
        }

        #endregion

        #region Private Static Functions

        /// <summary>
        /// Actually does the encryption/decryption
        /// </summary>
        private static string Process(string Input, string Key)
        {
            ASCIIEncoding Encoding = new ASCIIEncoding();
            byte[] InputArray = Encoding.GetBytes(Input);
            byte[] KeyArray = Encoding.GetBytes(Key);
            byte[] OutputArray = new byte[InputArray.Length];
            int Position = 0;
            for (int x = 0; x < InputArray.Length; ++x)
            {
                OutputArray[x] = (byte)(InputArray[x] ^ Key[Position]);
                ++Position;
                if (Position >= Key.Length)
                {
                    Position = 0;
                }
            }
            return Encoding.GetString(OutputArray);
        }

        #endregion
    }
}